﻿using SmartCA.Infrastructure.DomainBase;
using SmartCA.Infrastructure.RepositoryFramework.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartCA.Infrastructure.RepositoryFramework
{
    public static class RepositoryFactory
    {

        // 用字典进行强制单一模式
        private static Dictionary<string, object> repositories = new Dictionary<string, object>();


        public static TRepository GetRepository<TRepository, TEntity>()
            where TRepository : class, IRepository<TEntity>
            where TEntity : EntityBase
        {
            TRepository repository = default(TRepository);
            string interfaceShortName = typeof(TRepository).Name;

            // 查看提供者是否已经创建在cache中
            if (!RepositoryFactory.repositories.ContainsKey(interfaceShortName))
            {
                // not where, create it

                // Get the repositoryMappingsConfiguration config section
                RepositorySettings settings = (RepositorySettings)ConfigurationManager.GetSection(RepositoryMappingConstants.RepositoryMappingsConfigurationSectionName);

                // Create the repository,and cast it to the interface specified
                repository = Activator.CreateInstance(Type.GetType(settings.RepositoryMappings[interfaceShortName].RepositoryFullTypeName)) as TRepository;

                // Add the new provider instance to the cache
                RepositoryFactory.repositories.Add(interfaceShortName, repository);
            }
            else
            {
                // The provider was in the cache. so retrieve it
                repository = (TRepository)RepositoryFactory.repositories[interfaceShortName];
            }
            return repository;
        }

    }
}
